<template>
	<view class="m-m">
		<map style="width: 100%; height: 80vh;" :latitude="coords.latitude" :longitude="coords.longitude"
			:markers="markers" @callouttap="handleCalloutTap"></map>
		<view class="m-box">
			<!-- <view class="m-title">极护汽车美容中心</view> -->
			<!-- markers -->
			<view class="m-title">{{markers[index].title}}</view>
			<view class="m-mid">
				<uni-rate size="18" :readonly="true" :value="markers[index].star" />
				<view class="star">{{markers[index].star}}分</view>
			</view>
			<view class="m-time">营业时间:{{markers[index].businessHours}}</view>
			<view class="m-adress">地址:{{markers[index].detailedAddress}}</view>
			<image style="width: 17vw;" mode="aspectFit" :src="markers[index].images[0]" class="m-img"></image>
			<view class="m-botton">
				<view @tap="showPopup" class="m-b1">联系门店</view>
				<view @tap="appointment" class="m-b2">立即预约</view>
			</view>
		</view>

		<!-- 弹出层 -->
		<uni-popup ref="isPopupShow" @change="onPopupChange" type="bottom">
			<view class="popup-content">
				<view class="popup-phone">{{ markers[index].phoneNumber}}</view>
				<view class="popup-buttons">
					<view @click="makeCall" class="popup-button call">呼叫</view>
					<view @click="closePopup" class="popup-button cancel">取消</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import request from '@/utils/request.js';

const isCartLayerVisible = ref(false); // 购物车弹层是否可见
	const isPopupShow = ref(null); // 控制弹出层显示
	const index=ref(1);
	
	
	// 显示弹出层
	const showPopup = () => {
		isPopupShow.value.open();

	};

	const appointment = () => {
		// 存储数据
		if(index.value==0){
			index.value=1
		}
		 uni.setStorageSync('maintenancedetail', JSON.stringify(markers.value[index.value]));
		 console.log("markers",markers.value);
		 console.log("index",index.value);
		 console.log("1111",markers.value[index.value]);
		console.log('存储数据', JSON.stringify(markers.value[index.value]));
		uni.navigateTo({
			url: '/pages/maintenancedetail/maintenancedetail'
		})
	}
	// 关闭弹出层
	const closePopup = () => {
		isPopupShow.value.close();
	};

	// 拨打电话
	const makeCall = () => {
		// 在这里实现拨打电话逻辑
		uni.makePhoneCall({
			phoneNumber: markers.value[1].phoneNumber,
			success: () => {
				uni.showToast({
					title: '正在拨打电话...',
					icon: 'none',
				});
			},
			fail: (err) => {
				uni.showToast({
					title: '拨打电话失败',
					icon: 'none',
				});
				console.error('拨打电话失败:', err);
			},
		});
		closePopup(); // 拨打成功后关闭弹出层
	};

	// 监听弹出层状态变化
	const onPopupChange = (e) => {
		console.log('弹出层状态:', e.show);
	};



	var QQMapWX = require('../../static/qqmap-wx-jssdk.min.js');
	var qqmapsdk = new QQMapWX({
		key: 'HCABZ-7K3KM-33W6S-62YLC-T7INS-J5F7U'
		// key: 'JM5BZ-DP3KC-ZRY2F-AMLUB-MNFOT-BSBG6'
	});
	const coords = ref({
		latitude: 0, // 主干道交汇处
		longitude: 0
	})
	let star = ref(3) //星数
	const markers = ref([{ //占位对象,预留给本机地址
			id: 0,
			latitude: 0,
			longitude: 0,
			iconPath: dataUri,
			width: 30,
			height: 30,
			callout: {
				content: "附近门店>",
				bgColor: "#f0f9ff",
				borderRadius: 8,
				padding: 12,
				textAlign: 'center',
				display: 'ALWAYS'
			}
		}
		//,
		// {
		// 	id: 1,
		// 	latitude: 34.74821 + 0.0015, // 主干道交汇处
		// 	longitude: 113.61332 - 0.002,
		// 	// iconPath: '/static/garage.png',  // 保养工位图标
		// 	title: "云洗快修连锁(中州大道店)",
		// 	width: 40,
		// 	height: 40,
		// 	callout: {
		// 		content: "24小时服务 | 当前空闲工位：3\n特色：全合成机油买三送一\n电话：400-886-1234",
		// 		color: '#1890ff',
		// 		borderRadius: 8,
		// 		padding: 12,
		// 		display: 'ALWAYS'
		// 	}
		// }
	])

	const handleCalloutTap = (e) => {
		const markerId = e.detail.markerId
		const targetMarker = markers.value.find(m => m.id === markerId)
		console.log('触发的标记点ID:', e.detail.markerId) // 验证所有callout点击事件
		if (targetMarker?.id === 0) { // 定位点气泡
			uni.navigateTo({
				url: '/pages/maintenancelist/maintenancelist'
			})
		}else{
			index.value=e.detail.markerId
		}
				
	}
	const svgCode =
		`<svg t="1740814889904" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6591" width="200" height="200"><path d="M124.695273 583.68H71.68a71.68 71.68 0 0 1 0-143.36h53.038545A393.937455 393.937455 0 0 1 440.482909 124.741818V71.68a71.610182 71.610182 0 1 1 143.220364 0v53.061818a393.914182 393.914182 0 0 1 315.741091 315.578182h53.038545a71.68 71.68 0 0 1 0 143.36h-53.038545a393.914182 393.914182 0 0 1-315.741091 315.578182v53.061818a71.610182 71.610182 0 1 1-143.220364 0v-53.061818A393.937455 393.937455 0 0 1 124.718545 583.68zM512.069818 744.96A232.96 232.96 0 1 0 279.04 512 232.96 232.96 0 0 0 512.069818 744.96z m0-89.832727A143.127273 143.127273 0 1 1 655.290182 512 143.127273 143.127273 0 0 1 512.069818 655.127273z m0 0" fill="#3379E4" p-id="6592"></path></svg>`;
	const encodedSvg = encodeURIComponent(svgCode)
		.replace(/'/g, '%27')
		.replace(/"/g, '%22');
	let dataUri = `data:image/svg+xml;charset=utf8,${encodedSvg}`;
	const handleGetLocation = async () => {
		try {
			// 获取位置信息
			const res = await uni.getLocation({
				type: 'wgs84',
				enableHighAccuracy: true
			})

			// 更新经纬度
			coords.value = {
				latitude: res.latitude,
				longitude: res.longitude
			}
			// 在位置信息获取成功后再发起请求
			request({
				url: `/liu/geo/radius?latitude=${coords.value.latitude}&longitude=${coords.value.longitude}&radius=3000`,
				method: 'get',
			}).then(res => {

				// res.forEach(marker => {
				// 	marker.id = Number(marker.id); // 强制转换为数字
				// 	marker.width = marker.width || 35; // 默认值 35
				// 	marker.height = marker.height || 35; // 默认值 35
				// });
				console.log('请求成功:', res);
				markers.value = markers.value.concat(res)
				console.log("商家", markers.value)
			}).catch(err => {
				console.error('请求失败:', err);
			});
			await updateMarkerSize(coords.value);
			// 添加标记点（可选）unshift
			markers.value[0] = {
				id: 0,
				latitude: res.latitude,
				longitude: res.longitude,
				iconPath: dataUri, // 自定义图标路径
				width: 30,
				height: 30,
				callout: {
					content: "附近门店>",
					bgColor: "#f0f9ff",
					borderRadius: 8,
					padding: 12,
					textAlign: 'center',
					display: 'ALWAYS' // 支持BYCLICK/ALWAYS两种模式[7](@ref)
				}
			}
			console.log('定位成功:', res)
		} catch (error) {
			console.error('定位失败:', error)
			uni.showToast({
				title: '获取位置失败',
				icon: 'none'
			})
		}
	}
	onMounted(() => {
		handleGetLocation()
	})

	// 计算两点间直线距离（米）
	const calculateDistance = (lat1, lng1, lat2, lng2) => {
		// qqmapsdk.search({

		// })

		// 检查输入是否为数字
		if (
			typeof lat1 !== 'number' ||
			typeof lng1 !== 'number' ||
			typeof lat2 !== 'number' ||
			typeof lng2 !== 'number'
		) {
			console.error('Invalid coordinates:', lat1, lng1, lat2, lng2);
			return Promise.resolve(0); // 返回默认值
		}

		return new Promise((resolve) => {

			qqmapsdk.calculateDistance({
				mode: 'straight',
				from: {
					latitude: lat1,
					longitude: lng1
				},
				to: [{
					latitude: lat2, //
					longitude: lng2 //'113.62493'
				}],
				success: (res) => {
					if (res.status === 0 && res.result && res.result.elements && res.result
						.elements[0]) {
						resolve(res.result.elements[0].distance);
					} else {
						resolve(0); // 默认值，避免 undefined
					}
				},
				fail: (err) => {
					console.error('计算距离失败:', err);
					resolve(0); // 默认值，避免 undefined
				}
			});
		});
	};
	//​动态调整图标尺寸逻辑
	const updateMarkerSize = async (currentCoords) => {
		const BASE_SIZE = 35; // 基础尺寸
		const MAX_SIZE = 55; // 最大尺寸
		const RANGE = 3000; // 生效范围（3公里）

		const updatedMarkers = await Promise.all(markers.value.map(async marker => {
			if (marker.id === 0) return marker; // 跳过定位点
			// 获取距离并动态计算尺寸
			const distance = await calculateDistance(
				currentCoords.latitude, currentCoords.longitude,
				marker.latitude, marker.longitude
			);
			console.log('距离', distance);
			return {
				...marker,
				width: distance < RANGE ?
					Math.round(MAX_SIZE - (distance / RANGE) * (MAX_SIZE - BASE_SIZE)) : BASE_SIZE,
				height: distance < RANGE ?
					Math.round(MAX_SIZE - (distance / RANGE) * (MAX_SIZE - BASE_SIZE)) : BASE_SIZE
			};
		}));
		console.log(markers.value); // {0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}, 5: {…}}
		markers.value = updatedMarkers;
		console.log(updatedMarkers); //undefined
	};
</script>
<style>
	.m-m {
		/* background-color: #0000ff */
		width: 100vw;
		height: 100vh;
		overflow: hidden;
		/* 隐藏可能溢出的内容 */
	}

	.m-box {
		position: relative;
		margin: 10px;

	}

	.m-title {
		font-weight: 700;
	}

	.star {
		font-size: 12px;
		position: absolute;
		left: 110px;
		top: 0;
	}

	.m-img {
		position: absolute;
		right: 40px;
		top: -80px;
		z-index: -1;
	}

	.m-mid {
		position: relative;
		/* background-color: #000; */
	}

	.m-time {
		font-size: 14px;
	}

	.m-adress {
		font-size: 14px;
	}

	.m-botton {
		display: flex;
		justify-content: space-between;
		/* 两端对齐 */
		align-items: center;
		margin-top: 5px;
		width: calc(100% - 20px);
		/* 修正宽度计算 */
		/* background-color: #000000; */
		padding: 10px 0;
		/* 增加垂直间距 */
	}

	.m-b1,
	.m-b2 {
		width: 45%;
		/* 保留间距 */
		height: 30px;
		text-align: center;
		line-height: 30px;
		border-radius: 15px;
		/* 移除绝对定位 */
	}

	.m-b1 {
		background-color: #efefef
	}

	.m-b2 {
		background-color: #ff4e4e;
		color: #ffffff;

	}


	/* 弹出层内容样式 */
	.popup-content {
		width: 100vw;
		padding: 40px;
		background-color: #ffffff;
		border-radius: 10px 10px 0 0;
		text-align: center;
		position: absolute;
		bottom: -40px;
	}

	.popup-phone {
		font-size: 18px;
		color: #333333;
		margin-bottom: 20px;
	}

	.popup-buttons {
		display: flex;
		justify-content: space-between;
	}

	.popup-button {
		width: 48%;
		height: 40px;
		line-height: 40px;
		border-radius: 5px;
		color: #ffffff;
		font-size: 16px;
	}

	.popup-button.call {
		background-color: #ff4e4e;
	}

	.popup-button.cancel {
		background-color: #efefef;
		color: #333333;
	}
</style>